package com.example.demo.configuration;

import com.example.demo.security.filter.CustomUsernamePasswordFilter;
import com.example.demo.security.handler.LoginFailureHandler;
import com.example.demo.security.handler.LoginSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * describe:
 *
 * @author lianying
 * @date 2020/12/03
 */
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    private ProviderManager providerManager;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                //其他url都需要认证
                .mvcMatchers("/admin/**").hasRole("ADMIN")
                .mvcMatchers("/user/**").hasRole("USER")
                .mvcMatchers("/app/**").permitAll()
                .and()
                //设置登录页url,允许全部访问
                .formLogin().disable()
                //登录成功跳转到首页/
                //关闭跨域请求保护
                .csrf().disable()
                .addFilterBefore(loginFilter(), UsernamePasswordAuthenticationFilter.class)
                //如果需要自定义存储session，理论上是配置sessionManagement
//                .sessionManagement()
        ;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
    }

    @Override
    protected AuthenticationManager authenticationManager() throws Exception {
        return providerManager;
    }

    @Bean
    public CustomUsernamePasswordFilter loginFilter(){
        CustomUsernamePasswordFilter customUsernamePasswordFilter=new CustomUsernamePasswordFilter(providerManager);
        customUsernamePasswordFilter.setAuthenticationFailureHandler(new LoginFailureHandler());
        customUsernamePasswordFilter.setAuthenticationSuccessHandler(new LoginSuccessHandler());
        return customUsernamePasswordFilter;
    }

}
